package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.DimUtil;
import com.atguigu.gmall.realtime.utils.ThreadPoolUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;

import java.util.Collections;
import java.util.concurrent.ExecutorService;

/**
 * Author: Felix
 * Date: 2021/12/3
 * Desc: 异步维度关联类
 * 模板方法设计模式：
 *      在父类中定义实现某一个功能的核心算法的骨架，具体的实现延迟到子类中去完成；
 *      这样做的好处是，在不改变父类核心算法骨架的前提下，每一个子类中都可以有自己不同的实现方式
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> implements DimJoinFunction<T>{

    private ExecutorService executorService;

    private String tableName;

    public DimAsyncFunction(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        executorService = ThreadPoolUtil.getInstance();
    }

    /**
     * @param obj          流中处理对象
     * @param resultFuture
     * @throws Exception
     */
    @Override
    public void asyncInvoke(T obj, ResultFuture<T> resultFuture) throws Exception {
        //开启多个线程
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                //--发送异步请求完成维度关联的具体实现---
                try {
                    long start = System.currentTimeMillis();
                    //获取维度的主键
                    String key = getKey(obj);
                    //根据维度的主键 查询维度对象
                    JSONObject dimInfoJsonObj = DimUtil.getDimInfo(tableName, key);
                    //将维度对象中的属性值  赋值给流中的业务对象相关属性
                    if (dimInfoJsonObj != null) {
                        join(dimInfoJsonObj,obj);
                    }
                    long end = System.currentTimeMillis();
                    System.out.println("异步查询耗时：" +(end - start) + "毫秒");

                    //获取数据库交互的结果并发送给ResultFuture的回调函数
                    resultFuture.complete(Collections.singleton(obj));
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("异步的维度关联发生了异常");
                }
            }
        });
    }
}